﻿using log4net;
using NCP.Model;
using NCP.Service;
using NCP.Util;
using SqlSugar.Extensions;
using System.Configuration;
using System.Web.Mvc;
using System.Web.Mvc.Filters;

namespace WebApp.Filters
{
    public class AuthenAttribute : FilterAttribute, IAuthenticationFilter
    {
        private ILog logger = LogManager.GetLogger(typeof(AuthenAttribute));
        private string loginAction = ConfigurationManager.AppSettings["LoginAction"];

        public void OnAuthentication(AuthenticationContext filterContext)
      {
            if (filterContext.HttpContext.Session[Keys.UserID.ToString()] == null)
            {
                //重新设置session
                if (filterContext.HttpContext.Request.Cookies[Keys.UserID.ToString()] != null
                    && !string.IsNullOrEmpty(filterContext.HttpContext.Request.Cookies[Keys.UserID.ToString()].Value) )
                {
                    string userId = EncryptionDes.Decrypt(filterContext.HttpContext.Request.Cookies[Keys.UserID.ToString()].Value);
                    MemberService mService = UnityConfig.Resolve<MemberService>();
                    Member member = mService.Get(userId.ObjToInt());
                    if (userId == "-11" && member == null)
                        member = new Member() { Id = -11, Name = "系统管理员", Code = "sysadmin" };
                    if (member != null)
                    {
                        filterContext.HttpContext.Session[Keys.User.ToString()] = member;
                        filterContext.HttpContext.Session[Keys.UserID.ToString()] = member.Id;
                        return;
                    }
                }
                //通过his访问
                string url = filterContext.HttpContext.Request.Url.ToString();
                if (url.Contains("userID"))
                {
                    if (filterContext.HttpContext.Request.QueryString["userID"].ToString() != "")
                    {
                        string userId = EncryptionDes.Decrypt(filterContext.HttpContext.Request.QueryString["userID"].ToString());
                        MemberService mService = UnityConfig.Resolve<MemberService>();
                        Member member = mService.GetByStaffCode(userId);
                        if (userId == "-11" && member == null)
                            member = new Member() { Id = -11, Name = "系统管理员", Code = "sysadmin" };
                        if (member != null)
                        {
                            filterContext.HttpContext.Session[Keys.User.ToString()] = member;
                            filterContext.HttpContext.Session[Keys.UserID.ToString()] = member.Id;
                            return;
                        }
                    }
                }
                filterContext.Result = new RedirectResult(loginAction);
            }
        }

        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {

        }
    }
}